package com.appcenter.application.service;

import com.appcenter.application.dto.roles.RoleDto;
import com.appcenter.application.expand.ObjectFinal;
import com.appcenter.application.input.permission.GetPermissionsServiceInput;
import com.appcenter.application.input.role.*;
import com.appcenter.application.mapper.AppsMapper;
import com.appcenter.application.mapper.RolesMapper;
import com.appcenter.application.model.Apps;
import com.appcenter.application.model.Roles;
import com.appcenter.application.output.role.*;
import com.appcenter.jz.Logger.BusinessLogger;
import com.appcenter.jz.Logger.LoggerGenre;
import com.appcenter.jz.app.CurrentUser;
import com.appcenter.jz.unit.ObjectUnit;
import com.appcenter.jz.config.ErrorJsonResult;
import com.appcenter.jz.page.PagedResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static org.apache.http.util.TextUtils.isBlank;

@Service
public class RoleService {
    @Autowired
    RolesMapper rolesMapper;

    @Autowired
    AppsMapper appsMapper;

    @Autowired
    PermissionService permissionService;

    @Autowired
    ObjectFinal objectFinal;

    /**
     *  创建人:Coke
     *  备注: 创建角色信息
     *  时间: 2019/4/26 14:04 
     *  参数: 
     */
    public CreateRoleOutput CreateRole(CreateRoleInput input) throws Exception {
        CreateRoleOutput output = new CreateRoleOutput();
        int CodeCount = rolesMapper.getCodeCount(input.getItem().getAppId(), input.getItem().getRoleCode()).size();
        if (CodeCount > 0) {
            throw new ErrorJsonResult("1000061", "角色编号已存在！");
        }
        int NameCount=rolesMapper.getCodeCount(input.getItem().getAppId(), input.getItem().getRoleName()).size();
        if (NameCount > 0) {
            throw new ErrorJsonResult("1000062", "角色名称已存在！");
        }
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        Roles role=new Roles();
        role.setId(uuid);
        role.setAppId(input.getItem().getAppId());
        role.setAppId(input.getItem().getAppId());
        role.setRoleCode(input.getItem().getRoleCode());
        role.setRoleName(input.getItem().getRoleName());
        role.setDescription(input.getItem().getDescription());

        role.setValidStatus(true);
        role.setCreateTime(new Date());
        role.setCreateUserId(CurrentUser.getUserId());
        rolesMapper.insertSelective(role);
        BusinessLogger.Info(LoggerGenre.Add, "添加角色信息", input);
        RoleDto item = new RoleDto();
        BeanUtils.copyProperties(role,item);
        output.setItem(item);
        return output;
    }
    /**
     *  创建人:Coke
     *  备注: 删除角色信息
     *  时间: 2019/4/26 14:04 
     *  参数: 
     */

    public DeleteRoleOutput DeleteRole(DeleteRoleInput input) throws Exception {
        DeleteRoleOutput output = new DeleteRoleOutput();

        Roles oldRole = rolesMapper.selectByPrimaryKey(input.getItem().getId());
        oldRole.setValidStatus(false);
        BusinessLogger.Info(LoggerGenre.Delete, "删除角色信息", input);
        rolesMapper.updateByPrimaryKey(oldRole);
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 修改角色信息
     *  时间: 2019/4/26 14:05 
     *  参数: 
     */
    public EditRoleOutput EditRole(EditRoleInput input) throws Exception {
        EditRoleOutput output = new EditRoleOutput();
        int CodeCount = rolesMapper.getCodeCountNoId(input.getItem().getAppId(), input.getItem().getRoleCode(),input.getItem().getId()).size();
        if (CodeCount > 0) {
            throw new ErrorJsonResult("1000061", "角色编号已存在！");
        }
        int NameCount=rolesMapper.getCodeCountNoId(input.getItem().getAppId(), input.getItem().getRoleName(),input.getItem().getId()).size();
        if (NameCount > 0) {
            throw new ErrorJsonResult("1000062", "角色名称已存在！");
        }
        Roles role=rolesMapper.selectByPrimaryKey(input.getItem().getId());
        role.setAppId(input.getItem().getAppId());
        role.setAppId(input.getItem().getAppId());
        role.setRoleCode(input.getItem().getRoleCode());
        role.setRoleName(input.getItem().getRoleName());
        role.setDescription(input.getItem().getDescription());
        rolesMapper.updateByPrimaryKey(role);
        BusinessLogger.Info(LoggerGenre.Update, "更新角色信息", input);
        RoleDto item = new RoleDto();
        BeanUtils.copyProperties(role,item);
        output.setItem(item);
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 获取角色信息
     *  时间: 2019/4/26 14:05 
     *  参数: 
     */
    public GetRolesOutput GetRoles(GetRolesInput input) throws Exception {
        GetRolesOutput output = new GetRolesOutput();

        Example roleExample = new Example(Roles.class);
        Example.Criteria criteriaKeyword = roleExample.createCriteria();
        if(!isBlank(input.getKeyword())){
            criteriaKeyword.orLike("roleCode", "%"+input.getKeyword()+"%");
            criteriaKeyword.orLike("roleName", "%"+input.getKeyword()+"%");
        }
        roleExample.and(criteriaKeyword);
        Example.Criteria appCriteria = roleExample.createCriteria();
        appCriteria.andEqualTo("validStatus",true);
        appCriteria.andIn("appId",objectFinal.GetPermissionAppIds(ObjectFinal.APP_CODE,CurrentUser.getUserCode()));
        if(!isBlank(input.getAppId())){
            appCriteria.andEqualTo("appId",input.getAppId());
        }
        roleExample.and(appCriteria);


        PageHelper.startPage(input.getPage().getPageNo(),input.getPage().getPageSize(),"id desc");
        List<Roles> ls = rolesMapper.selectByExample(roleExample);
        PageInfo<Roles> page = new PageInfo<>(ls);
        List<RoleDto> newls = new ArrayList<RoleDto>();
        for (int i = 0; i < ls.size(); i++) {
            RoleDto appDto=new RoleDto();
            BeanUtils.copyProperties(ls.get(i), appDto);
            newls.add(appDto);
        }
        BusinessLogger.Info(LoggerGenre.View, "获取角色信息", input);
        output.setItems(new PagedResult<RoleDto>(newls, (int)page.getTotal()));
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 加载角色信息
     *  时间: 2019/4/26 14:23
     *  参数: 
     */
    public PageLoadOutput PageLoad(PageLoadInput input) throws Exception {
        PageLoadOutput output = new PageLoadOutput();
        output.setApps(objectFinal.GetPermissionApps(ObjectFinal.APP_CODE,CurrentUser.getUserCode()));
        output.setItems(GetRoles(input).getItems());
        return output;
    }


}
